package se.mbaeumer.fxtodo.core.util.dataimport;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import se.mbaeumer.fxtodo.core.model.EnumICSInfoType;
import se.mbaeumer.fxtodo.core.model.EnumPriority;
import se.mbaeumer.fxtodo.core.model.EnumTaskStatus;
import se.mbaeumer.fxtodo.core.model.ICSInfo;

import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.component.VEvent;

public class ICSReader {
	private String filename;
	private FileInputStream fileInputStream;
	private net.fortuna.ical4j.model.Calendar icsCalendar;
	private List<ICSInfo> icsInfos = new ArrayList<ICSInfo>();

	public ICSReader(String filename) throws IOException, ParserException{
		this.filename = filename;
		this.init();
	}
	
	private void init() throws IOException, ParserException{
		this.fileInputStream = new FileInputStream(this.filename);
		CalendarBuilder calendarBuilder = new CalendarBuilder();
		this.icsCalendar = calendarBuilder.build(this.fileInputStream);
	}
	
	@SuppressWarnings("unchecked")
	public void readFromFile(){
		// get all events
		for (VEvent vEvent : (List<VEvent>) this.icsCalendar.getComponents("VEVENT")){
			ICSInfo ics = new ICSInfo();
			if (vEvent.getSummary().getValue() == null){
				continue; 
			}else{
				ics.setSummary(vEvent.getSummary().getValue()); 
			}
			
			if (vEvent.getDescription().getValue() == null){
				ics.setDescription("");
			}else{
				ics.setDescription(vEvent.getDescription().getValue());
			}
			
			if (vEvent.getStartDate().getDate() == null){
				continue;
			}else{
				ics.setStartTime(vEvent.getStartDate().getDate());
			}
			
			if (vEvent.getEndDate() == null 
					|| vEvent.getEndDate().getDate() == null){
				ics.setEndTime(new DateTime());
			}else{
				ics.setEndTime(vEvent.getEndDate().getDate());
			}
			
			if (vEvent.getStatus() == null 
					|| vEvent.getStatus().getValue() == null){
				ics.setStatusString(EnumTaskStatus.Open.toString());
			}else{
				ics.setStatusString(vEvent.getStatus().getValue());
			}
			
			if (vEvent.getPriority() == null 
					|| vEvent.getPriority().getValue() == null){
				ics.setPriorityString(EnumPriority.Normal.toString());
			}else{
				ics.setPriorityString(vEvent.getPriority().getValue());
			}
			
			ics.setICSInfoType(EnumICSInfoType.Event);
			
			if (vEvent.getCreated() == null 
					|| vEvent.getCreated().getDateTime() == null){
				ics.setCreated(new DateTime());
			}else{
				ics.setCreated(vEvent.getCreated().getDateTime());
			}
			
			this.icsInfos.add(ics);
		}
	}

	public List<ICSInfo> getIcsInfos() {
		return icsInfos;
	}
}
